package deng.java.examples;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.jboss.classloading.spi.vfs.dependency.VFSClassLoaderPolicyModule;
import org.jboss.classloading.spi.vfs.metadata.VFSClassLoaderFactory;
import org.jboss.virtual.VirtualFile;

public class PatternBasedVFSClassLoaderPolicyModule extends
		VFSClassLoaderPolicyModule {
			
	/**
	 * 
	 */
	private static final long serialVersionUID = -7342660197394720054L;

	/** Our cached vfs roots */
	private VirtualFile[] vfsRoots;
	
	public PatternBasedVFSClassLoaderPolicyModule(
			VFSClassLoaderFactory classLoadingMetaData, String contextName) {
		super(classLoadingMetaData, contextName);
	}

	/**
	 * Get the virtual file roots
	 * 
	 * @return the roots
	 */
	protected VirtualFile[] determineVFSRoots() {
		if (vfsRoots != null)
			return vfsRoots;

		List<String> roots = getRoots();
		if (roots == null) {
			vfsRoots = new VirtualFile[0];
		} else {
			List<VirtualFile> vfsRootsList = new ArrayList<VirtualFile>();
			for (int i = 0; i < roots.size(); ++i) {
				String patternedRoot = roots.get(i);				
				List<String> expandedRoots = expandPattern(patternedRoot); 				
				for (String root : expandedRoots) {
					try {
						URI uri = new URI(root);
						vfsRootsList.add(getVirtualFile(uri));
					} catch (RuntimeException e) {
						throw e;
					} catch (Exception e) {
						throw new RuntimeException("Error creating VFS file for "
								+ root, e);
					}
				}
			}
			this.vfsRoots = vfsRootsList.toArray(new VirtualFile[vfsRootsList.size()]);
		}
		return vfsRoots;
	}

	private List<String> expandPattern(String patternedRoot) {
		List<String> list = new ArrayList<String>();
		if (patternedRoot.contains("*")) {
			// TODO: implement it.
		}
		return list;
	}

	@Override
	public void reset() {
		super.reset();
		vfsRoots = null;
	}
}
